package com.cyt.reward.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.util.StrUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.BaseUtil;
import com.cyt.base.util.DictCode;
import com.cyt.base.util.ErrorCode;
import com.cyt.reward.dao.RewardStaffDao;
import com.cyt.reward.model.po.RewardShop;
import com.cyt.reward.model.po.RewardStaff;
import com.cyt.reward.model.vo.RewardStaffVo;
import com.cyt.reward.service.RewardShopService;
import com.cyt.reward.service.RewardStaffService;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.SysFileService;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.sys.util.FilePathUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 打赏功能-员工管理Service层实现类
 *
 * @author rong yuan
 * @date 2019-7-24 14:21:33
 */
@Service("rewardStaffService")
public class RewardStaffServiceImpl extends BaseServiceImpl<RewardStaff> implements RewardStaffService {

    @Resource
    private RewardStaffDao rewardStaffDao;
    @Resource
    private RewardShopService rewardShopService;
    @Resource
    private SysFileService sysFileService;

    @Autowired
    public void setBaseDao(RewardStaffDao rewardStaffDao) {
        this.baseDao = rewardStaffDao;
    }

    /**
     * 分页查询
     *
     * @param rewardStaffVo 接受参数对象
     * @param pageNum       分页数
     * @param pageSize      每页显示条数
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-7-24 14:21:33
     */
    @Override
    public ReturnResult page(RewardStaffVo rewardStaffVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<RewardStaffVo> list = rewardStaffDao.selectByCondition(rewardStaffVo);
        PageInfo<RewardStaffVo> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 添加或更新
     *
     * @param rewardStaffVo 参数接受对象
     * @param sysUser       当前用户
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-7-24 14:21:33
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(RewardStaffVo rewardStaffVo, SysUser sysUser) {
        if (StringUtils.isBlank(rewardStaffVo.getPassword())) {
            RewardShop rewardShop = new RewardShop();
            rewardShop.setApplyId(rewardStaffVo.getApplyId());
            rewardShop.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
            rewardShop = rewardShopService.selectOne(rewardShop);
            if (rewardShop == null || StringUtils.isBlank(rewardShop.getPassword())) {
                return new ReturnResult(ErrorCode.CODE_1, "请先设置默认密码");
            } else {
                rewardStaffVo.setPassword(rewardShop.getPassword());
            }
        }
        if (checkJobNum(rewardStaffVo.getId(), rewardStaffVo.getApplyId(), rewardStaffVo.getJobNum())) {
            return new ReturnResult(ErrorCode.CODE_1, "该工号已被使用");
        }
        if (checkMobile(rewardStaffVo.getId(), rewardStaffVo.getApplyId(), rewardStaffVo.getMobile())) {
            return new ReturnResult(ErrorCode.CODE_1, "该手机号已被使用");
        }
        if (StrUtil.isEmpty(rewardStaffVo.getId())) {
            RewardStaff rewardStaff = new RewardStaff(sysUser);
            rewardStaff.setApplyId(rewardStaffVo.getApplyId());
            rewardStaff.setMemberId(rewardStaffVo.getMemberId());
            rewardStaff.setJobNum(rewardStaffVo.getJobNum());
            rewardStaff.setName(rewardStaffVo.getName());
            rewardStaff.setMobile(rewardStaffVo.getMobile());
            rewardStaff.setPassword(rewardStaffVo.getPassword());
            rewardStaff.setStars(Double.parseDouble(rewardStaffVo.getStars()));
            rewardStaff.setTotalMoney(Double.parseDouble(rewardStaffVo.getTotalMoney()));
            rewardStaff.setHaveMoney(Double.parseDouble(rewardStaffVo.getHaveMoney()));
            rewardStaff.setAccount(rewardStaffVo.getAccount());
            rewardStaff.setStaffType(rewardStaffVo.getStaffType());
            int num = rewardStaffDao.insert(rewardStaff);
            if (num > 0) {
                return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
            } else {
                return new ReturnResult(ErrorCode.CODE_1, BaseConstant.DATABASE_ERROR_INSERT);
            }
        } else {
            RewardStaff rewardStaff = rewardStaffDao.selectByPrimaryKey(rewardStaffVo.getId());
            rewardStaff.setApplyId(rewardStaffVo.getApplyId());
            rewardStaff.setMemberId(rewardStaffVo.getMemberId());
            rewardStaff.setJobNum(rewardStaffVo.getJobNum());
            rewardStaff.setName(rewardStaffVo.getName());
            rewardStaff.setMobile(rewardStaffVo.getMobile());
            rewardStaff.setPassword(rewardStaffVo.getPassword());
            rewardStaff.setStars(Double.parseDouble(rewardStaffVo.getStars()));
            rewardStaff.setTotalMoney(Double.parseDouble(rewardStaffVo.getTotalMoney()));
            rewardStaff.setHaveMoney(Double.parseDouble(rewardStaffVo.getHaveMoney()));
            rewardStaff.setAccount(rewardStaffVo.getAccount());
            rewardStaff.setStaffType(rewardStaffVo.getStaffType());
            rewardStaff.setUpdateTime(new Date());
            rewardStaff.setUpdateUser(sysUser.getId());
            int num = rewardStaffDao.updateByPrimaryKey(rewardStaff);
            if (num > 0) {
                return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
            } else {
                return new ReturnResult(ErrorCode.CODE_1, BaseConstant.DATABASE_ERROR_UPDATE);
            }
        }
    }

    private boolean checkJobNum(String id, String applyId, String jobNum) {
        RewardStaffVo rewardStaffVo = new RewardStaffVo();
        rewardStaffVo.setApplyId(applyId);
        rewardStaffVo.setJobNum(jobNum);
        rewardStaffVo.setRemoveTag(DictCode.BASE_REMOVE_TAG_NORMAL);
        RewardStaff rewardStaff = rewardStaffDao.selectOneByCondition(rewardStaffVo);
        if (StringUtils.isBlank(id)) {
            return rewardStaff != null;
        } else {
            return rewardStaff != null && !rewardStaff.getId().equals(id);
        }
    }

    private boolean checkMobile(String id, String applyId, String mobile) {
        RewardStaffVo rewardStaffVo = new RewardStaffVo();
        rewardStaffVo.setApplyId(applyId);
        rewardStaffVo.setMobile(mobile);
        rewardStaffVo.setRemoveTag(DictCode.BASE_REMOVE_TAG_NORMAL);
        RewardStaff rewardStaff = rewardStaffDao.selectOneByCondition(rewardStaffVo);
        if (StringUtils.isBlank(id)) {
            return rewardStaff != null;
        } else {
            return rewardStaff != null && !rewardStaff.getId().equals(id);
        }
    }

    /**
     * 根据条件逻辑删除
     *
     * @param rewardStaffVo 参数接受对象
     * @param sysUser       当前用户
     * @return ReturnResult
     * @author rong yuan
     * @date 2019-7-24 14:21:33
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(RewardStaffVo rewardStaffVo, SysUser sysUser) {
        //要修改的字段
        RewardStaff rewardStaff = new RewardStaff();
        rewardStaff.setRemoveTag(BaseConstant.REMOVE_TAG_YES);
        rewardStaff.setUpdateUser(sysUser.getId());
        rewardStaff.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(RewardStaff.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(rewardStaffVo.getId())) {
            criteria.andIn("id", Arrays.asList(rewardStaffVo.getId().split(",")));
        }
        criteria.andEqualTo("removeTag", BaseConstant.REMOVE_TAG_NO);
        rewardStaffDao.updateByExampleSelective(rewardStaff, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 根据条件查询单个对象
     *
     * @param rewardStaffVo 参数接受对象
     * @return RewardStaff
     * @author rong yuan
     * @date 2019/7/25 09:49
     */
    @Override
    public RewardStaff selectOneByCondition(RewardStaffVo rewardStaffVo) {
        return rewardStaffDao.selectOneByCondition(rewardStaffVo);
    }

    /**
     * 导入数据
     *
     * @param request 请求对象
     * @param file    文件对象
     * @param catalog 文件保存自定义目录
     * @param update  1、不更新已存在数据，2、更新存在数据
     * @param applyId 应用ID
     * @return ReturnResult
     * @author rong yuan
     * @date 2019/7/26 15:58
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult importData(HttpServletRequest request, MultipartFile file, String catalog, String update, String applyId, SysUser sysUser) {
        ReturnResult returnResult = sysFileService.fileUpload(file, request, catalog, BaseConstant.FILE_TYPE_EXECL);
        if (ErrorCode.CODE_0 == returnResult.getCode()) {
            String filePath = FilePathUtil.acceptCheckRealPath(request) + returnResult.getData().toString();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            List<RewardStaff> rewardStaffList = ExcelImportUtil.importExcel(new File(filePath), RewardStaff.class, params);
            if (rewardStaffList != null && rewardStaffList.size() > 0) {
                RewardStaffVo rewardStaffVo = new RewardStaffVo();
                rewardStaffVo.setApplyId(applyId);
                for (RewardStaff rewardStaff : rewardStaffList) {
                    rewardStaffVo.setJobNum(rewardStaff.getJobNum());
                    rewardStaffVo.setMobile(rewardStaff.getMobile());
                    RewardStaff po = rewardStaffDao.selectOneByCondition(rewardStaffVo);
                    if (po == null) {
                        rewardStaff.setId(BaseUtil.uId());
                    } else {
                        rewardStaff.setId(po.getId());
                        rewardStaff.setMemberId(po.getMemberId());
                    }
                    if (checkJobNum(rewardStaff.getId(), rewardStaff.getApplyId(), rewardStaff.getJobNum())
                            || checkMobile(rewardStaff.getId(), rewardStaff.getApplyId(), rewardStaff.getMobile())) {
                        break;
                    }
                    rewardStaff.setApplyId(applyId);
                    rewardStaff.setStars((double) 5);
                    rewardStaff.setTotalMoney((double) 0);
                    rewardStaff.setHaveMoney((double) 0);
                    rewardStaff.setRemoveTag(DictCode.BASE_REMOVE_TAG_NORMAL);
                    rewardStaff.setCreateTime(new Date());
                    rewardStaff.setCreateUser(sysUser.getId());
                    rewardStaff.setUpdateTime(new Date());
                    rewardStaff.setUpdateUser(sysUser.getId());
                    if (po == null) {
                        rewardStaffDao.insert(rewardStaff);
                    } else {
                        rewardStaffDao.updateByPrimaryKey(rewardStaff);
                    }
                }
            }
        }
        return returnResult;
    }
}